import { toNumber } from "../common/StringUtil"
import { Sequelize } from 'sequelize-typescript'
// import { sequelize } from '../modules/BaseDao'
class Pager{
  static pager:Pager=new Pager();
  private firstRecNoCurPage!: number // 每一页的第一条记录号是多少
  private pageSize: number =4 // 每一页总共最大多少条记录
  private curPageNo: number = 1 // 当前是第几页,默认第1页
  private totalPageNum: number = 0
  private curPageDataList: any[] = []
  //获取每一页第一条
  getFirstRecNoCurPage(curPageNo_: string,pageSize_:string = '0'){
    this.curPageNo=toNumber(curPageNo_) || this.curPageNo;
    this.pageSize=toNumber(pageSize_) || this.pageSize;
    this.firstRecNoCurPage=(this.curPageNo-1)*this.pageSize;
    return this.firstRecNoCurPage;
  }
  get PageSize(){
    return this.pageSize;
  }
  // 获取总页数
  getTotalPageNum(totalRecNum: number) {
    if(totalRecNum%this.pageSize===0){
      this.totalPageNum=totalRecNum/this.pageSize
    } else{
      this.totalPageNum=Math.floor(totalRecNum/this .pageSize)+1
    }
    return this.totalPageNum
  }
  //保存当前页数据[保存返回给前端的分页相关数据]
savecurPageData(_curPageDataList: any[], _totalpageNum?: number, _curPageNo?: string){
  this.curPageDataList= _curPageDataList;
}
 // 当前页数据[获取返回给前端的分页相关数据]
getcurPageData(){
  return {
    urPageNo:this.curPageNo,
    curPageDataList:this.curPageDataList,
    totalPageNum:this.totalPageNum
  }
}
}
type PageParamsType = [curPageNo: string, basePagerSql: string,
  recTotalNumSql:string, countPageField: string]
export function pagerDecoraotr(sequelize:Sequelize){
  return (targetPrototype:any,methodname:string,dataProps:PropertyDescriptor){
    const targetMethod = dataProps.value;
    dataProps .value = async (...args: PageParamsType) =>{
      const [curPageNo,basePagerSql,recTotalNumSgl,countPageFieldl] = args
      const firstRecNo = Pager.pager.getFirstRecNoCurPage(curPageNo)
      const sql=`${basePagerSql} ${firstRecNo},${Pager.pager.PageSize}`
      const curPageDataList =(await sequelize.query(sql))[0];
      const totalRecNumObj = (await sequelize.query(`${recTotalNumSgl}`))[0][0];
      Pager.pager.getTotalPageNum(totalRecNumObj[`count(${countPageFieldl})`])
      Pager.pager.savecurPageData(curPageDataList)
    }
  }
}

export default Pager.pager;
